import pickle
import base64
from django_redis import get_redis_connection


def merge_cart(request, user, response):
    # 获取参数
    cookie_cary = request.COOKIES.get("cart")
    # 判断cookie中是否有数据
    if not cookie_cary:
        return response
    # 转换cookie数据为字典
    cookie_dict = pickle.loads(base64.b64decode(cookie_cary.encode()))

    # 获取redis数据
    redis_conn = get_redis_connection("cart")
    cart_dict = redis_conn.hgetall("cart_%s" % user.id)  # 获取这个键名的全部值
    cart_selected_list = redis_conn.smembers("cart_selected_%s" % user.id)  # 获取set合集里的全部值
    # 合并数据到redis
    for sku_id,count_selected in cookie_dict.items():
        redis_conn.hset("cart_%s" % user.id, sku_id, count_selected["count"])  # 获取到当前用户的set数据
        redis_conn.sadd("cart_selected_%s" % user.id, sku_id)  # 获取到当前用户的勾选状态

    # 清除cookie数据
    response.delete_cookie("cart")
    # 返回响应
    return response